<?php

namespace Tests;

use GuzzleHttp\Client;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    protected $token;

    /**
     * 获取用户token
     *
     * @return string[]
     */
    public function getAuthHeader()
    {
        // 用户登录
        $username = 'tanfan1';
        $response = $this->post('wx/auth/login', [
            'username' => $username,
            'password' => '1234567',
        ]);
        // 获取token
        $token = $response->getOriginalContent()['data']['token'] ?? '';
        $this->token = $token;
        return ['Authorization' => "Bearer {$token}"];
    }

    public function assertLitemallApiGet($uri, $ignore = [])
    {
        return $this->assertLitemallApi($uri, 'get', [], $ignore);
    }

    public function assertLitemallApiPost($uri, $data = [], $ignore = [])
    {
        return $this->assertLitemallApi($uri, 'post', $data);
    }

    // 比较2个返回结果
    public function assertLitemallApi($uri, $method = "get", $data = [], $ignore = [])
    {
        $url = env('APP_URL','');
        $client = new Client();
        if ($method == "get") {
            $response1 = $this->get($uri, $this->getAuthHeader());
            $response2 = $client->get($url.$uri, ['headers' => ['X-Litemall-Token' => $this->token]]);
        } else {
            $response1 = $this->post($uri, $data, $this->getAuthHeader());
            $response2 = $client->post($url.$uri, [
                'headers' => ['X-Litemall-Token' => $this->token],
                'json' => $data,
            ]);
        }
        $content1 = $response1->getContent();
        echo "litemall=>".json_encode(json_decode($content1),JSON_UNESCAPED_UNICODE).PHP_EOL;
        $content1 = json_encode($content1, true);
        $content2 = $response2->getBody()->getContents();
        echo "mcshop=>{$content2}".PHP_EOL;
        $content2 = json_encode($content2, true);
        //过滤掉不需要比较的键值
        foreach ($ignore as $key) {
            unset($content1[$key]);
            unset($content2[$key]);
        }
        $this->assertEquals($content1, $content2);
        //$response1->assertJson($content2);
    }
}
